<template>
  <view>
    <view class="search-box">
      <uni-search-bar  @input="input"  :radius="100" cancel-button="none"></uni-search-bar>
    </view>
    <!-- 搜索建议列表 -->
    <view class="sugg-list" v-if="searchResult.length !==0">
      <view class="sugg-item" v-for="(item, index) in searchResult" :key="index" @click="gotoDetail(item.good_id)">
        <view class="goods-name">{{item.goods_name}}</view>
       <uni-icons type="arrowright" size="16"></uni-icons>
      </view>  
    </view>
    <!-- 搜索历史 -->
    <view class="history-box" v-else>
      <view class="history-title">
        <text>搜索历史</text>
        <uni-icons type="trash" size="16" @click="cleanHistory"></uni-icons>
      </view>
      <view class="history-list">
        <uni-tag :text="item" v-for="(item, index) in histories" :key="index" @click="gotoGoodsList(item)"></uni-tag>
      </view>
    </view>
  </view>
</template>

<script>
  export default {
    data() {
      return {
        //延时器的timeId
        timer: null,
        //搜索关键词
        kw: '',
        //搜索结果
        searchResult: [],
        //搜索历史
        historyList: ['a', 'b', 'c']
        
      };
    },
    methods: {
      input(e) {
        //清除延时器
        clearTimeout(this.timer)
        //重新启动延时器
        this.timer = setTimeout(() => {
          //发起搜索请求
          this.kw = e
          this.getSearchResult()                 
        }, 500)
        
      },
      //根据关键词获取搜索结果
      async getSearchResult() {
        if (this.kw === '') {
          this.searchResult = []
          return
        }
        const {data:res} = await uni.$http.get('/api/public/v1/goods/qsearch', {query: this.kw})
        if (res.meta.status !== 200) return uni.$showMsg()
        this.searchResult = res.message
        //查询到搜索结果后，将搜索关键词添加到历史记录中
        this.saveSearchHistory()
      },
      gotoDetail(good_id) {
        uni.navigateTo({
          url: '/subpkg/goods_detail/goods_detail?good_id=' + good_id
        })
      },
      //将搜索关键词添加到历史记录中
      saveSearchHistory() {
        //1.将搜索关键词转成数组
        const set = new Set(this.historyList)
        //2.将数组中的关键词删除
        set.delete(this.kw)
        //3.将关键词添加到数组的最前面
        set.add(this.kw)
        //4.将set结构转成数组
        this.historyList = Array.from(set)
        //5.将历史记录持久化存储到本地
        uni.setStorageSync('kw', JSON.stringify(this.historyList))
        console.log(JSON.stringify(this.historyList))
      },
      //清空搜索历史
      cleanHistory() {
        //清空保存的搜索历史
        this.historyList = []
        //清空本地存储中搜索历史
        uni.setStorageSync('kw', '[]')
      },
      //点击搜索历史中的关键词，搜索商品列表
      gotoGoodsList(kw) {
        uni.navigateTo({
          url: '/subpkg/goods_list/goods_list?query=' + kw
        })
        }
      
    },
    computed: {
      histories() {
        //将搜索历史进行反转
        return [...this.historyList].reverse()
      }
    },
    onLoad() {
      //将搜索历史从本地存储中读取出来，并赋值给historyList
      this.historyList = JSON.parse(uni.getStorageSync('kw') || '[]')
    }
  }
</script>

<style lang="scss">
  .search-box {
    position: sticky;
    top: 0;
    z-index: 999;
  }
  .sugg-list {
    padding: 0 5px;
    .sugg-item {
      font-size: 12px;
      padding: 13px 0;
      border-bottom: 1px solid #efefef;
      display: flex;
      align-items: center;
      justify-content: space-between;
      .goods-name {
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        margin-right: 3px;
      }
    }
  }
  .history-box {
    padding: 0 5px;
    .history-title {
      display: flex;
      justify-content: space-between;
      height: 40px;
      align-items: center;
      font-size: 13px;
      border-bottom: 1px solid #efefef;
    }
    .history-list {
      display: flex;
      flex-wrap: wrap;
      .uni-tag {
        margin-top: 5px;
        margin-right: 5px;
        }
    }
  }

</style>
